var EditEntry = {
   actor: null,
   categories: null,
   tabbox: null,
   links: null,
   elements: {},
   editor: {
      doc: null,
      control: null,
      init: function() {
         this.control = document.getElementById('editor');
         this.doc = this.control.contentWindow.document;
         /*
         this.control.setAttribute("src","chrome://atomic/content/blank.html");
         var currentEdit = this;
         setTimeout(function() {
            try {
               currentEdit.control.makeEditable("html",true);
               //currentEdit.doc = currentEdit.control.contentWindow.document;
            } catch (ex) {
               alert(ex);
            }
         },
            500
         );
          */
      },
      bold: function() {
         this.doc.execCommand("bold", false, null);
      },
      italic: function() {
         this.doc.execCommand("italic", false, null);
      },
      link: function() {
      }
   },
   init: function(obj) {
      document.title = obj.title;
      this.entry = obj.entry;
      this.actor = obj;
      this.elements['title'] = document.getElementById('title');
      this.elements['summary'] = document.getElementById('summary');
      this.categories = new Categories(document.getElementById('categories'));
      this.links = new Links(document.getElementById('links'));
      this.tabbox = document.getElementById('entry-info');
      this.editor.init();
      this.initEntry();
   },
   initEntry: function() {
      try {
         //alert("Initializing entry");
         var title = this.entry.getTitle();
         this.elements['title'].value = title.xml.textContent;
         var summary = this.entry.getSummary();
         if (summary) {
            this.elements['summary'].value = summary.xml.textContent;
         }
         var categories = this.entry.getCategories();
         for (var i=0; i<categories.length; i++) {
            this.categories.addCategory(
               categories[i].scheme,
               categories[i].term,
               categories[i].value
            );
         }
         var links = this.entry.getLinks();
         for (var i=0; i<links.length; i++) {
            if (links[i].rel!="edit") {
               this.links.addLink(
                  links[i].rel,
                  links[i].href,
                  links[i].type,
                  links[i].title
               );
            }
         }
         var currentApp = this;
         currentApp.initContent();
      } catch (ex) {
         alert(ex);
      }
   },
   initContent: function() {
      var content = this.entry.getContent();
      if (content) {
         if (content.src) {
            if (content.type.indexOf("text")==0 ||
                content.type.indexOf("application/xml")==0 ||
                content.type.indexOf("application/xquery")==0 ||
                content.type.indexOf("application/x-javascript")==0 ||
                content.type.indexOf("+xml")>0) {
               document.getElementById('src-content').hidden = false;
               document.getElementById('src-location').value = "src="+content.src+", type="+content.type;
               content.getMedia({
                  onSuccess: function(status,xml,text) {
                     document.getElementById('src-text').value = text;
                  },
                  onFailure: function(status,xml,text) {
                     alert("Could not retrieve meida entry content due to status "+status);
                  }
               });
            } else {
               document.getElementById('src-content-noedit').hidden = false;
               document.getElementById('src-content-url').setAttribute("href",content.getLocation());
            }
         } else if (content.type=="text" || content.type=="html") {
            document.getElementById('text-content').hidden = false;
            document.getElementById('entry-text').value = content.xml.textContent;
         } else if (content.type=="xhtml") {
            this.sourceTab = false;
            document.getElementById('xhtml-content').hidden = false;
            var div = content.getXHTMLContent();
            var sourceEditor = document.getElementById('entry-xhtml-source');
            var serializer = new XMLSerializer();
            sourceEditor.value = serializer.serializeToString(div);
            var xhtmlDoc = this.editor.doc;
            this.editor.control.focus();
            var editorDiv = xhtmlDoc.getElementById('content');
            /*
            var editorDiv = document.getElementById('xhtml-div');
             */
            if (div) {
               var current = div.firstChild;
               while (current) {
                  editorDiv.appendChild(editorDiv.ownerDocument.importNode(current,true));
                  current = current.nextSibling;
               }
            }
            this.editor.control.contentWindow.tinyMCE.execCommand("mceAddControl",false,"content");         
            //xhtmlDoc.designMode = "on";
         } else if (content.type=="text/xml" || content.type=="application/xml" || content.type.indexOf("+xml")>0) {
            document.getElementById('xml-content').hidden = false;
            var node = content.getNodeContent();
            if (node) {
               var sourceEditor = document.getElementById('entry-xml');
               var serializer = new XMLSerializer();
               sourceEditor.value = serializer.serializeToString(node);
            }
         } else {
            document.getElementById('non-editable-mime-type').value = content.type;
            document.getElementById('non-editable-content').hidden = false;
         }
      } else {
         document.getElementById('no-content').hidden = false;
      }
   },
   switchToXHTMLTab: function(index) {
      if (index==0) {
         this.switchToXHTMLFormatted();
      } else {
         this.switchToXHTMLSource();
      }
   },
   switchToXHTMLFormatted: function() {
      if (!this.sourceTab) {
         return;
      }
      this.sourceTab = false;
      var result = this.parseXHTMLSource();
      if (result.wellFormed) {
         this.editor.control.contentWindow.tinyMCE.execCommand("mceRemoveControl",false,"content");         
         var xhtmlDoc = this.editor.doc;
         this.editor.control.focus();
         var editorDiv = xhtmlDoc.getElementById('content');
         DOMUtil.clearChildren(editorDiv);
         var current = result.div.firstChild;
         while (current) {
            editorDiv.appendChild(editorDiv.ownerDocument.importNode(current,true));
            current = current.nextSibling;
         }
         this.editor.control.contentWindow.tinyMCE.execCommand("mceAddControl",false,"content");         
      } else {
         document.getElementById("xhtml-content-tabs").selectedIndex = 1;
      }
   },
   switchToXHTMLSource: function() {
      if (this.sourceTag) {
         return;
      }
      this.sourceTab = true;
      var xhtmlDoc = this.editor.doc;
      var xmlString = this.editor.control.contentWindow.tinyMCE.getContent();
      /*
      var editorDiv = xhtmlDoc.getElementById('content');
      var div = document.createElementNS("http://www.w3.org/1999/xhtml","div");
      var current = editorDiv.firstChild;
      while (current) {
         div.appendChild(document.importNode(current,true));
         current = current.nextSibling;
      }
      var serializer = new XMLSerializer();
       */
      var sourceEditor = document.getElementById('entry-xhtml-source');
      /*
      alert(serializer.serializeToString(editorDiv));
      alert(serializer.serializeToString(div));
      sourceEditor.value = serializer.serializeToString(div);
       */
      sourceEditor.value = "<div xmlns='http://www.w3.org/1999/xhtml'>\n"+xmlString+"\n</div>";
   },
   revertSrcXHTMLContent: function() {
      var sourceEditor = document.getElementById('entry-xhtml-source');
      var content = this.entry.getContent();
      var div = content.getXHTMLContent();
      if (div) {
         var serializer = new XMLSerializer();
         var xml = serializer.serializeToString(div);
         sourceEditor.value = xml;
      } else {
         alert("Cannot find div!");
      }

   },
   parseXHTMLSource: function() {
      var sourceEditor = document.getElementById('entry-xhtml-source');
      var desc = document.getElementById("xhtml-xml-errors");             
      DOMUtil.clearChildren(desc);
      var xmlParser = new DOMParser();
      var xmlDocument = xmlParser.parseFromString(sourceEditor.value, 'text/xml');
      var roottag = xmlDocument.documentElement; 
      var ok = true;
      if ((roottag.tagName == "parsererror") &&
          (roottag.namespaceURI == "http://www.mozilla.org/newlayout/xml/parsererror.xml")) {
         desc.appendChild(desc.ownerDocument.createTextNode(roottag.firstChild.textContent));
         ok = false;
      } else {
         if (roottag.localName!="div" ||
             roottag.namespaceURI!="http://www.w3.org/1999/xhtml") {
            ok = false
            desc.appendChild(desc.ownerDocument.createTextNode("The div wrapper element is missing."));
         }
      }
      return {
         wellFormed: ok,
         div: roottag
      }
   },
   parseXMLSource: function() {
      try {
         var desc = document.getElementById("xml-errors");             
         DOMUtil.clearChildren(desc);
         var xmlParser = new DOMParser();
         var xmlDocument = xmlParser.parseFromString(document.getElementById('entry-xml').value, 'text/xml');
         var roottag = xmlDocument.documentElement; 
         if ((roottag.tagName == "parsererror") &&
             (roottag.namespaceURI == "http://www.mozilla.org/newlayout/xml/parsererror.xml")) {
            desc.appendChild(desc.ownerDocument.createTextNode(roottag.firstChild.textContent));
         } else {
            return {
               wellFormed: true,
               node: roottag
            };
         }
      } catch (e) {
         desc.appendChild(desc.ownerDocument.createTextNode("Parse failed: "+e));
      }
      return {
         wellFormed: false
      };
   },
   parseSrcContent: function() {
      var xmlParser = new DOMParser();
      var xmlDocument = xmlParser.parseFromString(document.getElementById('src-text').value, 'text/xml');
      var roottag = xmlDocument.documentElement; 
      if ((roottag.tagName == "parsererror") &&
          (roottag.namespaceURI == "http://www.mozilla.org/newlayout/xml/parsererror.xml")) {
         alert("XML parsing error:\n"+roottag.firstChild.textContent);
      }
   },
   saveSrcContent: function() {
      this.entry.getContent().update(document.getElementById('src-text').value,{
         onSuccess: function() {
         },
         onFailure: function(status) {
            alert("Cannot update media entry content due to status "+status);
         }
      });
   },
   revertSrcContent: function() {
      this.entry.getContent().getMedia({
         onSuccess: function(status,xml,text) {
            document.getElementById('src-text').value = text;
         },
         onFailure: function(status,xml,text) {
            alert("Could not retrieve meida entry content due to status "+status);
         }
      });
   },
   createContent: function(type) {
      var content = this.entry.getContent(true);
      content.type = type;
      document.getElementById('no-content').hidden = true;
      if (type=="xhtml") {
         var div = content.xml.ownerDocument.createElementNS("http://www.w3.org/1999/xhtml","div");
         var p = content.xml.ownerDocument.createElementNS("http://www.w3.org/1999/xhtml","p");
         p.appendChild(content.xml.ownerDocument.createTextNode("Enter some text here."));
         div.appendChild(p);
         content.setNodeContent(div);
      } else if (type=="text/xml") {
         var root = content.xml.ownerDocument.createElementNS("","root");
         content.setNodeContent(root);
      }
      this.initContent();
   },
   doSave: function() {
      if (this.sourceTab) {
         var result = this.parseXHTMLSource()
         if (!result.wellFormed) {
            alert("Cannot save entry as the XHTML is not well-formed.");
            return;
         }
      }
      // Update entry
      var titleText = this.entry.getTitle();
      titleText.setTextContent(document.getElementById('title').value);
      titleText.type = "text";
      var summary = document.getElementById('summary').value;
      var summaryText = this.entry.getSummary();
      if (summary) {
         if (!summaryText) {
            summaryText = this.entry.getSummary(true);
         }
         summaryText.type = "text";
         summaryText.setTextContent(summary);
      } else if (summaryText) {
         this.entry.xml.removeChild(summaryText.xml);
      }
      this.updateCategories();
      this.updateLinks();
      this.updateContent();
      this.buttonsDisabled(true);
      this.actor.doSave(this);   
   },
   doCancel: function() {
      EditEntry.actor.doCancel();
      window.close();
   },
   updateCategories: function() {
      this.entry.removeAllCategories();
      var set = this.categories.getCategories();
      for (var i=0; i<set.length; i++) {
         this.entry.addCategory(set[i].scheme,set[i].term,set[i].value);
      }
      /*
      var serializer = new XMLSerializer();
      alert(serializer.serializeToString(this.entry.xml));
       */
      
   },
   updateLinks: function() {
      this.entry.removeAllLinks();
      var set = this.links.getLinks();
      for (var i=0; i<set.length; i++) {
         this.entry.addLink(set[i].rel,set[i].href,set[i].type,set[i].title);
      }
   },
   updateContent: function() {
      var content = this.entry.getContent();
      if (content) {
         if (content.src) {
            return;
         }
         if (content.type=="text" || content.type=="html") {
            content.setTextContent(document.getElementById('entry-text').value);
         } else if (content.type=="xhtml") {
            
            if (!this.sourceTab) {
               var xmlString = this.editor.control.contentWindow.tinyMCE.getContent();
               var sourceEditor = document.getElementById('entry-xhtml-source');
               sourceEditor.value = "<div xmlns='http://www.w3.org/1999/xhtml'>\n"+xmlString+"\n</div>";
               LOG.debug("From editor:\n"+sourceEditor.value);
            }
            var result = this.parseXHTMLSource();
            if (!result.wellFormed) {
               throw "XHTML source is not well-formed.";
            }
            content.setNodeContent(result.div);
            /*
            if (this.sourceTab) {
               var result = this.parseXHTMLSource();
               if (!result.wellFormed) {
                  throw "XHTML source is not well-formed.";
               }
               content.setNodeContent(result.div);
            } else {
               var editorDiv = this.editor.doc.getElementById('content');
               var newDiv = content.xml.ownerDocument.createElementNS("http://www.w3.org/1999/xhtml","div");
               var current = editorDiv.firstChild;
               while (current) {
                  newDiv.appendChild(newDiv.ownerDocument.importNode(current,true));
                  current = current.nextSibling;
               }
               content.setNodeContent(newDiv);
            }
             */
         } else if (content.type=="text/xml" || content.type=="application/xml" || content.type.indexOf("+xml")>0) {
            var result = this.parseXMLSource();
            if (!result.wellFormed) {
               throw "XML source is not well-formed.";
            }
            content.setNodeContent(result.node);
         }
      }
   },
   doDelete: function() {
      if (this.tabbox.selectedIndex==1) {
         if (confirm("Are you sure you want to delete the selected categories?")) {
            this.categories.deleteSelected();
         }
      } else if (this.tabbox.selectedIndex==2) {
         if (confirm("Are you sure you want to delete the selected links?")) {
            this.links.deleteSelected();
         }
      }
   },
   onSuccess: function() {
      setTimeout(function() { window.close(); },100);
   },
   onFailure: function(message) {
      var desc = document.getElementById('message');
      if (desc.firstChild) {
         desc.removeChild(desc.firstChild);
      }
      desc.appendChild(document.createTextNode(message));
      this.buttonsDisabled(false);
   },
   buttonsDisabled: function(flag) {
      document.getElementById('save').disabled = flag;
      document.getElementById('cancel').disabled = flag;
      document.getElementById('revert').disabled = flag;
   }
}
